package com.lgy.springcloud.controller;

import com.lgy.springcloud.entity.Payment;
import com.lgy.springcloud.loadbalance.MyLoadBanlance;
import com.lgy.springcloud.loadbalance.impl.MyLBImpl;
import com.lgy.springcloud.util.Constant;
import com.lgy.springcloud.util.R;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    DiscoveryClient discoveryClient;
    @Resource
    MyLoadBanlance myLoadBanlance;

    @Resource
    RestTemplate restTemplate;
    @RequestMapping("/list")
    public R list(){
        return restTemplate.getForObject(Constant.REST_PAYMENT_URL+"/pay", R.class);
    }
    @RequestMapping("/{id}")
    public R getOrder(@PathVariable("id")Long id){
        return restTemplate.getForObject(Constant.REST_PAYMENT_URL + "/pay/" + id, R.class);

    }
    @RequestMapping("/save")
    public R addOrder(Payment payment){
        return restTemplate.postForObject(Constant.REST_PAYMENT_URL+"/pay", payment, R.class);
    }
    @RequestMapping("/update")
    public void update(Payment payment){
       restTemplate.put(Constant.REST_PAYMENT_URL+"/pay",payment);
    }

    @RequestMapping("/lb")
    public String myLb(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances == null||instances.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance = myLoadBanlance.serviceInstance(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/pay",String.class);
    }
}
